package com.fenghongzhang.day011;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.provider.Telephony;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

/**
 * 1,权限名不一昂
 * 2,动态权限名也不一样
 * 3,url不一样
 * 4,字段不一样
 */
public class Main2Activity extends AppCompatActivity {
    private Button getSms;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        getSms = (Button) this.<View>findViewById(R.id.getSms);

        //2动态权限
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            requestPermissions(new String[]{Manifest.permission.READ_SMS},999);
        }

        getSms.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               //3
                ContentResolver contentResolver = getContentResolver();
                Cursor query = contentResolver.query(Telephony.Sms.CONTENT_URI, null, null, null, null);

                if(query != null){
                    while(query.moveToNext()){
                        String address = query.getString(query.getColumnIndex(Telephony.Sms.ADDRESS));
                        String body = query.getString(query.getColumnIndex(Telephony.Sms.BODY));
                        Toast.makeText(Main2Activity.this, address+body, Toast.LENGTH_SHORT).show();

                    }
                }
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == 999 && grantResults[0] == PackageManager.PERMISSION_GRANTED){

        }else{
            finish();
        }
    }
}
